const http = require("http");
const url = require("url");
const path = require("path");
const fs = require("fs");
const mime = require("mime");

const server = http.createServer((req, res) => {
  // 路径处理
  let { pathname, query } = url.parse(req.url);
  pathname = decodeURIComponent(pathname);
  let absPath = path.join(__dirname, pathname);
  console.log(pathname, absPath);
  // 目标资源状态处理
  fs.stat(absPath, (err, statObj) => {
    if (err) {
      res.statusCode = 404;
      res.end("Not Found");
      return;
    }

    if (statObj.isFile()) {
      fs.readFile(absPath, (err, data) => {
        res.setHeader("Content-type", mime.getType(absPath) + ";charset=utf-8");
        res.end(data);
      });
    } else {
      // 如果是目录，默认读取www文件下的index
      fs.readFile(path.join(absPath, "index.html"), (err, data) => {
        res.setHeader("Content-type", mime.getType(absPath) + ";charset=utf-8");
        res.end(data);
      });
    }
  });
});

server.listen(1234, () => {
  console.log("server is start.....");
});
